var FormData = require("form-data");
var fs = require("fs");
var http = require("http");
const download = require("download");
const path = require("path");
const option = {
	"content-type": "application/x-www-form-urlencoded",
	cookie:
		"AppKey=wxe2c44d06eac05e60;Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJhdWQiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJqdGkiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJpYXQiOjE1NDg3NDQzMDUsIm5iZiI6MTU0ODc0NDMwNSwiZXhwIjoxNTQ4NzUxNTA1LCJBcHBLZXkiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJVc2VySUQiOiIyNDAyMzkiLCJPcGVuSWQiOiJva0VFWDBaSkVPZS1zaU5WZnFnWkRiOEloRG9jIiwiQ3JlYXRlVGltZSI6IjIwMTgtMDgtMDYgMTM6NDA6MDQifQ.g5u9aIrTr6W22e2R_ThfsLeB1-uQpqadXp1EB8hTDfE",
	Referer:
		"https://servicewechat.com/wxe2c44d06eac05e60/devtools/page-frame.html",
	"User-Agent":
		"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36 wechatdevtools/1.02.1901230 MicroMessenger/6.7.3 webview/",
	"X-Platform": "Android"
};
const replaceImage = imageUrl => {
	return new Promise((resolve, reject) => {
		if (!imageUrl) {
			return reject();
		}
		download(imageUrl)
			.then(data => {
				var form = new FormData();
				form.append("file", data, {
					filename: `file.${path.extname(imageUrl)}`
				});

				var headers = form.getHeaders();
				headers.Cookie = option.cookie;

				var request = http.request(
					{
						method: "post",
						host: "common.zmwxxcx.com",
						path: "/upload/upload",
						headers: headers
					},
					function(res) {
						var str = "";
						res.on("data", function(buffer) {
							str += buffer;
						});
						res.on("end", () => {
							var result = JSON.parse(str);
							resolve(result.d);
						});
					}
				);
				form.pipe(request);
			})
			.catch(err => {
				reject(err);
			});
	});
};
module.exports = {
	replaceImage
};
